// src/pages/login.js
import { navigate } from 'gatsby'
import React from 'react'
import { useDispatch, useSelector } from 'react-redux'
import useInput from '../hooks/useInput'

export default function Login () {
  const email = useInput('')
  const password = useInput('')
  const dispath = useDispatch()
  const authReducer = useSelector(state => state.authReducer)
  if (authReducer.success) {
    // 已登录 跳转到首页
    navigate('/')
    return null
  }
  function displayErrors () {
    if (authReducer.errors) {
      return authReducer.errors.map((item, index) => <li key={index}>
        { item }
      </li>)
    }
    return null
  }
  function handleSubmit (e) {
    e.preventDefault()
    const emailValue = email.input.value
    const passwordValue =  password.input.value
    dispath({
      type: 'login',
      payload: {
        user: {
          email: emailValue,
          password: passwordValue
        }
      }
    })
  }

  return <div className="auth-page">
  <div className="container page">
    <div className="row">
      <div className="col-md-6 offset-md-3 col-xs-12">
        <h1 className="text-xs-center">Sign up</h1>
        <ul className="error-messages">
          { displayErrors() }
        </ul>
        <form onSubmit={handleSubmit}>
          <fieldset className="form-group">
            <input {...email.input} className="form-control form-control-lg" type="text" placeholder="Email" />
          </fieldset>
          <fieldset className="form-group">
            <input {... password.input} className="form-control form-control-lg" type="password" placeholder="Password" />
          </fieldset>
          <button className="btn btn-lg btn-primary pull-xs-right">
            Sign up
          </button>
        </form>
      </div>
    </div>
  </div>
</div>
}